import React, { useEffect, useRef } from 'react'
import * as echarts from 'echarts'
import { ICameraData } from '../interface/ICameraData'

interface IProps {
  data: ICameraData[]
}
interface IViolateType {
  name: string
  reg: RegExp
  count: number
}
export default function BreachType(props: IProps) {
  const data = props.data
  const el = useRef<HTMLDivElement | null>(null)
  const ec = useRef<echarts.ECharts | null>(null)
  useEffect(() => {
    ec.current = echarts.init(el.current as HTMLDivElement)
  }, [])
  useEffect(() => {
    //分析常见违纪类型
    const violateTypes: IViolateType[] = [
      { name: '讲师迟到', reg: /未进班/igm, count: 0 },
      { name: '讲师不在班', reg: /讲师不在班/igm, count: 0 },
      { name: '提前放学', reg: /放学/igm, count: 0 },
      { name: '没分享', reg: /未检查到课前分享/igm, count: 0 },
      { name: '迟到', reg: /迟到/igm, count: 0 },
      { name: '早退', reg: /早退/igm, count: 0 },
      { name: '看视频', reg: /无关视频/igm, count: 0 },
      { name: '打游戏', reg: /打游戏/igm, count: 0 },
      { name: '睡觉', reg: /睡觉/igm, count: 0 },
    ]
    data.forEach((item: ICameraData) => {
      violateTypes.forEach((_type: IViolateType) => {
        const num = item['存在问题'].match(_type.reg)?.length
        if (num) {
          _type.count += num
        }
      })
    })
    violateTypes.sort((a, b) => b.count - a.count)
    const x: string[] = []
    const y: number[] = []
    violateTypes.forEach(item => {
      x.push(item.name)
      y.push(item.count)
    });
    (ec.current as echarts.ECharts).setOption({
      title: {
        text: '违纪类型',
        left: 'center'
      },
      xAxis: {
        data: x,
        axisLabel: {
          rotate: -45
        }
      },
      yAxis: {},
      series: [{
        type: 'bar',
        data: y,
        label: {
          show: true
        }
      }]
    })
  }, [data])
  return (
    <div className="show" ref={el}></div>
  )
}
